<?php

namespace App\Model\System;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Eeofile
{

    /**
     * 计算文件存放目录
     * @param $file
     * @return string
     */
    static function makeUploadPath($file)
    {
        static $path=null;

        if(is_null($path)){
            $type = 'unfound';
            if($types = explode('/',$file->getMimeType())){
                $type = $types[0];
            }
            $hash = md5_file($file->getRealPath());
            $first = substr($hash,0,2);
            $second = substr($hash,-2);
            $path = self::baseDir() . "$type/$first/$second/";
        }
        return $path;
    }


    /**
     * 计算目标文件
     * @param $file
     * @return string
     */
    static function getUploadFileFullName($file)
    {
        return Self::makeUploadPath($file) . $file->getClientOriginalName();
    }



    /**
     * 获取文件的web访问目录
     * @param $fullPath
     * @return mixed
     */
    static function getWebPath($fullPath)
    {
        $base = self::baseDir();
        $fullPath = str_ireplace('\\','/', $fullPath);
        $dir = str_replace($base, '', $fullPath);
        return $dir;
    }


    /**
     * 获取文件的服务端存储目录
     * @param $path
     * @return string
     */
    static function getLocalPath($path)
    {
        return  self::baseDir() . $path;
    }


    /**
     * 获取文件存储的一级目录
     * @return mixed|string
     */
    static function baseDir()
    {
        $envDir = env('APP_UPLOAD_PATH');
        if($envDir[0]=='.'){
            $envDir = str_replace('.', '', $envDir);
            $base = dirname($_SERVER['DOCUMENT_ROOT']) . $envDir;
        }else{
            $base = $envDir;
        }
        $base = str_ireplace('\\','/', $base);
        return $base;
    }


    /**
     * 根据api url 获取绝对磁盘地址
     * @param $url  /api/file?u=image/bd/44/Hydrangeas.jpg
     * @return  string
     */
    static function getAbsoluteAddressForApiUrl($url)
    {
        $urls = explode('=', $url);
        $address = $urls[1];
        return self::getLocalPath($address);
    }

}
